package com.ptszyxx.popose.module.base.password.vm;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.utils.YActivityUtil;
import com.ysg.base.BaseViewModel;
import com.ysg.binding.command.BindingCommand;
import com.ysg.bus.event.SingleLiveEvent;
import com.ysg.http.BaseResponse;
import com.ysg.http.HttpUtils;
import com.ysg.http.callback.OnSuccessResult;
import com.ysg.http.data.CommonRepository;
import com.ysg.utils.YMD5Utils;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YToastUtil;

import java.util.HashMap;
import java.util.Map;

public class PasswordVM extends BaseViewModel<CommonRepository> {
    public ObservableField<String> passwordOld = new ObservableField<>();
    public ObservableField<String> passwordNew = new ObservableField<>();
    public ObservableField<String> passwordAgain = new ObservableField<>();

    public PasswordVM(@NonNull Application application, CommonRepository model) {
        super(application, model);
    }

    public UIChangeObservable uc = new UIChangeObservable();
    public class UIChangeObservable {
        public SingleLiveEvent onImageCodeEvent = new SingleLiveEvent<>();
    }


    public BindingCommand onSubmitCommand = new BindingCommand(()->requestPassword());


    private void requestPassword(){
        if (!check())return;

        Map<String, String> map = new HashMap<>();
        map.put("password", YMD5Utils.get(passwordOld.get()));
        map.put("newpassword", YMD5Utils.get(passwordNew.get()));
        map.put("surepassword", YMD5Utils.get(passwordAgain.get()));

        HttpUtils.getInstance()
                .data(model.passwordUpdate(map), this,
                        new OnSuccessResult() {
                            @Override
                            public void onSuccessResult(BaseResponse response) {
                                YToastUtil.showShort(R.string.update_success);
                                YActivityUtil.getInstance().close(PasswordVM.this);
                            }
                        });
    }


    private boolean check(){
        if (YStringUtil.isEmpty(passwordOld.get())){
            YToastUtil.showShort(R.string.password_old_tip);
            return false;
        }
        if (YStringUtil.isEmpty(passwordNew.get())){
            YToastUtil.showShort(R.string.password_new_tip);
            return false;
        }
        if (YStringUtil.noEq(passwordNew.get(), passwordAgain.get())){
            YToastUtil.showShort(R.string.password_no_eqait);
            return false;
        }
        return true;
    }
}
